package com.ryder.petmatediarybackend.module.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ryder.petmatediarybackend.common.enums.ResultCode;
import com.ryder.petmatediarybackend.common.exception.BusinessException;
import com.ryder.petmatediarybackend.module.admin.dto.UserQueryDTO;
import com.ryder.petmatediarybackend.module.admin.dto.UserRoleDTO;
import com.ryder.petmatediarybackend.module.admin.dto.UserUpdateDTO;
import com.ryder.petmatediarybackend.module.admin.service.AdminUserService;
import com.ryder.petmatediarybackend.module.admin.vo.UserPageVO;
import com.ryder.petmatediarybackend.module.auth.entity.SysRole;
import com.ryder.petmatediarybackend.module.auth.entity.SysUserRole;
import com.ryder.petmatediarybackend.module.auth.mapper.SysRoleMapper;
import com.ryder.petmatediarybackend.module.auth.mapper.SysUserRoleMapper;
import com.ryder.petmatediarybackend.module.pet.entity.SysUser;
import com.ryder.petmatediarybackend.module.pet.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述：管理员用户管理 Service 实现
 *
 * @author Ryder
 * @version 1.0
 * @since 1.0
 * 更新日期: 2025-10-31
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AdminUserServiceImpl implements AdminUserService {

    private final SysUserMapper sysUserMapper;
    private final SysRoleMapper sysRoleMapper;
    private final SysUserRoleMapper sysUserRoleMapper;

    @Override
    public Page<UserPageVO> pageUsers(UserQueryDTO dto, Long currentUserId) {
        // 如果按角色筛选，需要先找到拥有该角色的用户ID列表
        List<Long> filteredUserIds = null;
        if (StringUtils.hasText(dto.getRoleCode())) {
            // 根据角色编码查找角色ID
            LambdaQueryWrapper<SysRole> roleWrapper = new LambdaQueryWrapper<>();
            roleWrapper.eq(SysRole::getCode, dto.getRoleCode())
                    .eq(SysRole::getIsDeleted, 0);
            SysRole role = sysRoleMapper.selectOne(roleWrapper);
            
            if (role != null) {
                // 查找拥有该角色的用户ID
                LambdaQueryWrapper<SysUserRole> userRoleWrapper = new LambdaQueryWrapper<>();
                userRoleWrapper.eq(SysUserRole::getRoleId, role.getId())
                        .eq(SysUserRole::getIsDeleted, 0);
                List<SysUserRole> userRoles = sysUserRoleMapper.selectList(userRoleWrapper);
                filteredUserIds = userRoles.stream()
                        .map(SysUserRole::getUserId)
                        .collect(Collectors.toList());
                
                // 如果该角色没有用户，直接返回空页面
                if (filteredUserIds.isEmpty()) {
                    return new Page<>(dto.getCurrent(), dto.getSize());
                }
            } else {
                // 角色不存在，返回空页面
                return new Page<>(dto.getCurrent(), dto.getSize());
            }
        }

        // 构建查询条件
        Page<SysUser> page = new Page<>(dto.getCurrent(), dto.getSize());
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(dto.getUsername()), SysUser::getUsername, dto.getUsername())
                .like(StringUtils.hasText(dto.getNickname()), SysUser::getNickname, dto.getNickname())
                .eq(dto.getStatus() != null, SysUser::getStatus, dto.getStatus())
                .in(filteredUserIds != null, SysUser::getId, filteredUserIds)
                .ne(currentUserId != null, SysUser::getId, currentUserId) // 排除当前登录用户
                .eq(SysUser::getIsDeleted, 0)
                .orderByDesc(SysUser::getCreateTime);

        Page<SysUser> userPage = sysUserMapper.selectPage(page, wrapper);

        // 转换为VO
        Page<UserPageVO> voPage = new Page<>();
        BeanUtils.copyProperties(userPage, voPage, "records");
        List<UserPageVO> voList = userPage.getRecords().stream().map(user -> {
            UserPageVO vo = new UserPageVO();
            BeanUtils.copyProperties(user, vo);

            // 查询用户角色
            LambdaQueryWrapper<SysUserRole> roleWrapper = new LambdaQueryWrapper<>();
            roleWrapper.eq(SysUserRole::getUserId, user.getId())
                    .eq(SysUserRole::getIsDeleted, 0);
            List<SysUserRole> userRoles = sysUserRoleMapper.selectList(roleWrapper);

            if (!userRoles.isEmpty()) {
                List<Long> roleIds = userRoles.stream()
                        .map(SysUserRole::getRoleId)
                        .collect(Collectors.toList());

                // 查询角色信息
                List<SysRole> roles = sysRoleMapper.selectBatchIds(roleIds);
                vo.setRoles(roles.stream().map(SysRole::getName).collect(Collectors.toList()));
                vo.setRoleIds(roleIds);
            }

            return vo;
        }).collect(Collectors.toList());

        voPage.setRecords(voList);
        return voPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(UserUpdateDTO dto) {
        if (dto.getId() == null) {
            throw new BusinessException(ResultCode.BAD_REQUEST, "用户ID不能为空");
        }
        
        SysUser user = sysUserMapper.selectById(dto.getId());
        if (user == null || user.getIsDeleted() == 1) {
            throw new BusinessException(ResultCode.NOT_FOUND, "用户不存在");
        }

        // 检查手机号和邮箱是否重复
        if (StringUtils.hasText(dto.getPhone()) && !dto.getPhone().equals(user.getPhone())) {
            LambdaQueryWrapper<SysUser> phoneWrapper = new LambdaQueryWrapper<>();
            phoneWrapper.eq(SysUser::getPhone, dto.getPhone())
                    .eq(SysUser::getIsDeleted, 0)
                    .ne(SysUser::getId, dto.getId());
            if (sysUserMapper.selectCount(phoneWrapper) > 0) {
                throw new BusinessException(ResultCode.BAD_REQUEST, "手机号已存在");
            }
        }

        if (StringUtils.hasText(dto.getEmail()) && !dto.getEmail().equals(user.getEmail())) {
            LambdaQueryWrapper<SysUser> emailWrapper = new LambdaQueryWrapper<>();
            emailWrapper.eq(SysUser::getEmail, dto.getEmail())
                    .eq(SysUser::getIsDeleted, 0)
                    .ne(SysUser::getId, dto.getId());
            if (sysUserMapper.selectCount(emailWrapper) > 0) {
                throw new BusinessException(ResultCode.BAD_REQUEST, "邮箱已存在");
            }
        }

        BeanUtils.copyProperties(dto, user);
        sysUserMapper.updateById(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUser(Long userId) {
        SysUser user = sysUserMapper.selectById(userId);
        if (user == null || user.getIsDeleted() == 1) {
            throw new BusinessException(ResultCode.NOT_FOUND, "用户不存在");
        }

        user.setIsDeleted(1);
        sysUserMapper.updateById(user);

        // 删除用户角色关联
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId, userId)
                .eq(SysUserRole::getIsDeleted, 0);
        List<SysUserRole> userRoles = sysUserRoleMapper.selectList(wrapper);
        userRoles.forEach(userRole -> {
            userRole.setIsDeleted(1);
            sysUserRoleMapper.updateById(userRole);
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignRoles(UserRoleDTO dto) {
        SysUser user = sysUserMapper.selectById(dto.getUserId());
        if (user == null || user.getIsDeleted() == 1) {
            throw new BusinessException(ResultCode.NOT_FOUND, "用户不存在");
        }

        // 查询该用户所有的用户-角色关联记录（包括已删除的）
        LambdaQueryWrapper<SysUserRole> allWrapper = new LambdaQueryWrapper<>();
        allWrapper.eq(SysUserRole::getUserId, dto.getUserId());
        List<SysUserRole> allUserRoles = sysUserRoleMapper.selectList(allWrapper);

        // 将所有现有的有效角色标记为删除
        allUserRoles.stream()
                .filter(ur -> ur.getIsDeleted() == 0)
                .forEach(userRole -> {
                    userRole.setIsDeleted(1);
                    sysUserRoleMapper.updateById(userRole);
                });

        // 分配新角色
        for (Long roleId : dto.getRoleIds()) {
            SysRole role = sysRoleMapper.selectById(roleId);
            if (role == null || role.getIsDeleted() == 1) {
                throw new BusinessException(ResultCode.BAD_REQUEST, "角色ID " + roleId + " 不存在");
            }

            // 查找是否已存在该用户-角色组合记录（不管是否删除）
            SysUserRole existingUserRole = allUserRoles.stream()
                    .filter(ur -> ur.getRoleId().equals(roleId))
                    .findFirst()
                    .orElse(null);

            if (existingUserRole != null) {
                // 如果记录存在，将其恢复为有效状态
                existingUserRole.setIsDeleted(0);
                sysUserRoleMapper.updateById(existingUserRole);
            } else {
                // 如果记录不存在，插入新记录
                SysUserRole newUserRole = new SysUserRole();
                newUserRole.setUserId(dto.getUserId());
                newUserRole.setRoleId(roleId);
                newUserRole.setIsDeleted(0);
                sysUserRoleMapper.insert(newUserRole);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeRoles(Long userId, List<Long> roleIds) {
        SysUser user = sysUserMapper.selectById(userId);
        if (user == null || user.getIsDeleted() == 1) {
            throw new BusinessException(ResultCode.NOT_FOUND, "用户不存在");
        }

        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId, userId)
                .in(SysUserRole::getRoleId, roleIds)
                .eq(SysUserRole::getIsDeleted, 0);
        List<SysUserRole> userRoles = sysUserRoleMapper.selectList(wrapper);
        userRoles.forEach(userRole -> {
            userRole.setIsDeleted(1);
            sysUserRoleMapper.updateById(userRole);
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatus(Long userId, Integer status) {
        if (status != 0 && status != 1) {
            throw new BusinessException(ResultCode.BAD_REQUEST, "状态值无效");
        }

        SysUser user = sysUserMapper.selectById(userId);
        if (user == null || user.getIsDeleted() == 1) {
            throw new BusinessException(ResultCode.NOT_FOUND, "用户不存在");
        }

        user.setStatus(status);
        sysUserMapper.updateById(user);
    }
}

